package dshop.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

import appbase.jfinal.ext.ApiBaseController;
import appbase.utils.HttpRequestKit;
import appbase.utils.JsonUtil;
import dshop.kits.ApiKit;

public class ApiReadBodyParamInterceptor implements Interceptor{

	private static Logger log = Logger.getLogger(ApiReadBodyParamInterceptor.class);
	
	@Override
	public void intercept(Invocation ai) 
	{
		long start = System.currentTimeMillis();
		HttpServletRequest request = ai.getController().getRequest();
		
		log.info("----------------------------------------");
		log.info("请求URL：" + HttpRequestKit.currrentUrl(request));
		
		String encryptText = HttpRequestKit.readStream(request);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if (encryptText != null && !encryptText.isEmpty()) 
		{
			String jsonStr = ApiKit.decryptText(encryptText);
			paramMap = JsonUtil.toMap(jsonStr);
			log.info("参数：" + jsonStr);
		}else 
		{
			log.info("参数：{}");
		}
		
		request.setAttribute(ApiBaseController.ATTR_MOBILE_PARAM_MAP, paramMap);
		
		//跨域访问时处理
		/*if (request.getMethod().toUpperCase().equals("OPTIONS")) 
		{
			ApiBaseController ctrl = (ApiBaseController)ai.getController();
			ctrl.renderSuccess();
			return;
		}*/
		
		try {
			//Thread.sleep(1000 * 3);
			ai.invoke();
		} catch (Exception e) {
			e.printStackTrace();
			ApiBaseController ctrl = (ApiBaseController)ai.getController();
			ctrl.renderFail(e.getMessage());
		}
		
		request.removeAttribute(ApiBaseController.ATTR_MOBILE_PARAM_MAP);
		
		long costMs = System.currentTimeMillis() - start;
		log.info(" 执行消耗时间：" + costMs);
		log.info("----------------------------------------");
	}
	
}
